package com.promise.jokerdream.work.penguin

import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.utils.AppContext

// 巅峰之战工作
class PeakBattleWork(uin: String): BaseWork(uin) {
    
    private val gameApi = GameApi.Companion.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.Companion.getInstance(AppContext.get()) }
    
    override val name: String = "巅峰之战"
    
    override suspend fun executeWork(): WorkResult {
        try {
            // 1. 查询巅峰之战状态
            val queryResult = gameApi.queryPeakBattle()
            
            queryResult.foldWithApiException(
                onSuccess = { response ->
                    // 检查是否需要报名
                    if (response.status == 1 && response.userinfo.group == 0) {
                        val signupResult = gameApi.signupPeakBattle()
                        signupResult.foldWithApiException(
                            onSuccess = { signupResponse ->
                                historyManager.addHistory(name, signupResponse.getDescription())
                            },
                            onFailure = { code, msg ->
                                historyManager.addHistory(name, msg, code)
                            }
                        )
                    }
                    if (response.status == 2 && response.userinfo.group != 0) {
                        val claimResult = gameApi.claimPeakBattle()
                        claimResult.foldWithApiException(
                            onSuccess = { response ->
                                historyManager.addHistory(name, response.getDescription())
                            },
                            onFailure = { code, msg ->
                                if (msg != "您已经领取过了！") {
                                    historyManager.addHistory(name, msg, code)
                                }
                            }
                        )
                    }
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    return WorkResult.Failure(Exception(msg), msg)
                }
            )
            
            return WorkResult.Success
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            return WorkResult.Failure(e, e.message)
        }
    }
}